import { BuildingType, EntityType, UnitType } from '../../battle/Enums';
import { BuildingModel, UnitModel } from '../../battle/Model';
import { getUnitConfig, getBuildingConfig } from '../../battle/Const';

/**
 * 实体工厂类
 * 负责创建单位和建筑，并维护ID的唯一性
 */
export class EntityFactory {
    private static instance: EntityFactory = null;
    private nextUnitId: number = 1; // 单位唯一ID，两个玩家共用
    private nextBuildingId: number = 1; // 建筑唯一ID，两个玩家共用

    /**
     * 获取工厂单例
     */
    public static getInstance(): EntityFactory {
        if (!EntityFactory.instance) {
            EntityFactory.instance = new EntityFactory();
        }
        return EntityFactory.instance;
    }

    /**
     * 重置工厂状态
     */
    public reset(): void {
        this.nextUnitId = 1;
        this.nextBuildingId = 1;
    }

    /**
     * 创建单位
     * @param playerId 玩家ID
     * @param unitType 单位类型
     * @param position 位置
     * @param unitId 单位ID
     * @returns 创建的单位模型
     */
    public createUnit(playerId: string, unitType: UnitType, position: { x: number; y: number }, unitId: number): UnitModel {

        // 从配置中获取单位属性
        const unitConfig = getUnitConfig(unitType);
        const hp = unitConfig.hp;
        const attack = unitConfig.attack;

        const unit: UnitModel = {
            id: unitId,
            type: unitType,
            player: playerId,
            hp: hp,
            attack: attack,
            speed: unitConfig.speed,
            position: { ...position }
        };

        return unit;
    }

    /**
     * 创建建筑
     * @param playerId 玩家ID
     * @param buildingType 建筑类型
     * @param position 位置
     * @returns 创建的建筑模型
     */
    public createBuilding(playerId: string, buildingType: BuildingType, position: { x: number; y: number }, buildingId: number): BuildingModel {

        // 从配置中获取建筑属性
        const buildingConfig = getBuildingConfig(buildingType);
        const hp = buildingConfig.hp;

        const building: BuildingModel = {
            id: buildingId,
            type: buildingType,
            player: playerId,
            hp: hp,
            attack: buildingConfig.attack,
            position: { ...position }
        };

        return building;
    }

    /**
     * 获取下一个可用的单位ID
     * @returns 单位唯一ID
     */
    public getNextUnitId(): number {
        return this.nextUnitId++;
    }

    /**
     * 获取下一个可用的建筑ID
     * @returns 建筑唯一ID
     */
    public getNextBuildingId(): number {
        return this.nextBuildingId++;
    }
}